package org.rendao.service.base
{
	import com.googlecode.flexxb.FlexXBEngine;
	
	import flash.display.DisplayObject;
	import flash.utils.Dictionary;
	
	import mx.core.FlexGlobals;
	import mx.managers.PopUpManager;
	import mx.messaging.messages.HTTPRequestMessage;
	import mx.rpc.AsyncToken;
	import mx.rpc.Responder;
	import mx.rpc.events.FaultEvent;
	import mx.rpc.events.ResultEvent;
	import mx.rpc.http.HTTPService;
	import mx.utils.URLUtil;
	
	import org.rendao.control.MessagePopupWindow;
	import org.rendao.entity.TBFError;

	public class ServiceUtils
	{
		private static const XML_CONTENT_TYPE:String="text/xml";
		
		public static function callService(url:String,
										   successFunction:Function, 
										   content:Object = null,
										   faultFunction:Function = null,
										   params:Dictionary = null):void {
			var successExecution:Function=function(event:ResultEvent):void{
				var error:TBFError = convertToTBFError(event.result);
				if(error) {
					if(faultFunction != null) {
						faultFunction(error);
					}
					else {
						tbfErrorHandler(error);
					}
				}
				else {
					successFunction(event.result);
				}
			};
			sendRequest(url, content, successExecution, defaultFaultHandler, params);
		}
		
		private static function sendRequest(url:String, 
											content:Object, 
											result:Function, 
											fault:Function, 
											params:Dictionary):void {		
			
			var timestampUrl:String = constructTimestampUrl(url, params);
			var http:HTTPService=constructService(timestampUrl);
			http.request = content;
			var processResult:Function=function(event:ResultEvent):void {
				result(event);
			};
			http.method = content == null ? HTTPRequestMessage.GET_METHOD : HTTPRequestMessage.POST_METHOD;
			var responder:Responder=new Responder(processResult,fault);
			var call:AsyncToken = http.send();
			call.addResponder(responder);
		}
		
		private static function constructService(url:String):HTTPService {
			var http:HTTPService=new HTTPService();
//			http.url=GlobalModule.hostUrl + "/" + url;
			http.url=url;
			http.contentType=XML_CONTENT_TYPE;
			http.resultFormat=HTTPService.RESULT_FORMAT_E4X;
			http.headers = {accept:XML_CONTENT_TYPE};
			return http;
		}
		
		private static function constructTimestampUrl(url:String, params:Dictionary):String {
			url += "?uniqueId=" + new Date().time;
			for (var key:Object in params)
			{
				url += "&" + key.toString() + "=" + params[key];
			}
			return url;			
		}
		
		private static function defaultFaultHandler(event:FaultEvent):void {
			popupError("系统错误", event.message.toString());
		}

		private static function tbfErrorHandler(error:TBFError):void {
			popupError("错误", error.message);
		}
		
		private static function popupError(title:String, message:String):void {
			var win:MessagePopupWindow = new MessagePopupWindow();
			win.title = title;
			win.message = message;
			PopUpManager.addPopUp(win, FlexGlobals.topLevelApplication as DisplayObject, true);
			PopUpManager.centerPopUp(win);
		}
		
		private static function convertToTBFError(result:Object):TBFError {
			var resultXml:XML = result as XML;
			if(resultXml.name() == "tbf_error") {
				var e:Object = FlexXBEngine.instance.deserialize(result as XML, TBFError); 
				var error:TBFError = e as TBFError;
				return error;
			}
			return null;
		}
	}
}